package com.kkshop.domain.utility.security;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.userdetails.jdbc.JdbcDaoImpl;
import org.apache.log4j.Logger;
import org.hibernate.classic.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;

public class ExtendedJdbcDaoImpl extends JdbcDaoImpl {

    private static final Logger log = Logger.getLogger(ExtendedJdbcDaoImpl.class);

    private String[] userInfoObjectTypes;

    private SessionFactory sessionFactory;

    public UserDetails loadUserByUsername(String username) {
        try {
            UserDetails user = super.loadUserByUsername(username);
            Session session = sessionFactory.openSession();
            for (int i = 0; i < userInfoObjectTypes.length; i++) {
                Object userInfo = session.createQuery(
                        "from " + userInfoObjectTypes[i]
                                + " where username = '" + username + "'")
                        .uniqueResult();
                if (userInfo != null)
                    return new ExtendedUser(user.getUsername(), user
                            .getPassword(), user.isEnabled(), user
                            .getAuthorities(), userInfo);
            }
            return new ExtendedUser(user.getUsername(), user.getPassword(),
                    user.isEnabled(), user.getAuthorities());

        } catch (UsernameNotFoundException e) {
            log.error("Could not find user name", e);
            throw e;
        } catch (DataAccessException e) {
            log.error("Could not read user name", e);
            throw e;
        }
    }

    public void setUserInfoObjectTypes(String[] userInfoObjectTypes) {
        this.userInfoObjectTypes = userInfoObjectTypes;
    }

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
